package com.lgl.mes.common.util.org.easy.excel.aop.cell.inner;

import com.lgl.mes.common.util.org.easy.excel.aop.cell.CellInterceptorAdapter;
import com.lgl.mes.common.util.org.easy.excel.aop.cell.CellJoinPoint;
import com.lgl.mes.common.util.org.easy.excel.exception.ExcelException;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;

/**
 * 处理decimalFormat标签
 * @author lisuo
 *
 */
public class DecimalFormatCellInterceptor extends CellInterceptorAdapter {

	@Override
	public boolean supports(CellJoinPoint joinPoint) {
		return joinPoint.getFieldValue().getDecimalFormat() != null && joinPoint.getValue() != null;
	}

	@Override
	public Object executeImport(CellJoinPoint joinPoint) throws ExcelException {
		if(joinPoint.getValue() instanceof String){
			try {
				return joinPoint.getFieldValue().getDecimalFormat().parse(joinPoint.getValue().toString());
			} catch (ParseException e) {
				throw newExcelDataException(e.getMessage(), joinPoint);
			}
		}
		return super.executeImport(joinPoint);
	}

	@Override
	public Object executeExport(CellJoinPoint joinPoint) throws ExcelException {
		DecimalFormat decimalFormat = joinPoint.getFieldValue().getDecimalFormat();
		Object val = joinPoint.getValue();
		if(val instanceof String) {
			try {
				val = new BigDecimal(val.toString());
			}catch(Exception ignore) {}
		}
		return decimalFormat.format(val);
	}

}
